package testenv.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import testenv.model.entity.Child;
import testenv.model.entity.Parent;
import testenv.service.ChildService;
import testenv.service.ParentService;


@Controller
public class ParentChildEditorController {

	@Autowired
	private ParentService parentService; 
	
	@Autowired
	private ChildService childService;
	
	
	@ModelAttribute("parentList")
	public List<Parent> populateParentList() {
		return parentService.getParentList();
	}
	
	@ModelAttribute("childCount")
	public Integer populateChildCount() {
		return childService.getChildCount();
	}

	
	@RequestMapping(value="/parentchildeditor.do", method=RequestMethod.GET)
	public ModelMap processGet(ModelMap modelMap) {
		Parent parent = new Parent("Parent 1");
		
		childService.selectChild();
		
		modelMap.addAttribute("parent", parent);
		return modelMap;
	}
	
	
	@RequestMapping(value="/parentchildeditordeletechild.do", method=RequestMethod.GET)
	public String processDeleteChildGet(
			@RequestParam(required=true, value="childid") Integer childId,
			ModelMap modelMap) {
		
		childService.deleteChild(childId);
				
		return "redirect:/parentchildeditor.do";
	}	
	
	
	@RequestMapping(value="/parentchildeditordeleteparent.do", method=RequestMethod.GET)
	public String processDeleteParentGet(
			@RequestParam(required=true, value="parentid") Integer parentId,
			ModelMap modelMap) {
		
		parentService.deleteParent(parentId);
				
		return "redirect:/parentchildeditor.do";
	}	
	
	@RequestMapping(value="/parentchildeditor.do", method=RequestMethod.POST)
	public String processParentChildPost(
  		@ModelAttribute("parent") Parent parent, 
  		BindingResult result, 
  		SessionStatus status) {		
		
		parent.getChildSet().add(new Child("child1", 34, parent));
		parent.getChildSet().add(new Child("child2", 43, parent));
		parent.getChildSet().add(new Child("child3", 43, parent));
				
		parentService.saveParent(parent);
		
		return "redirect:parentchildeditor.do";
	}
	
}
